import { envList, deviceInfoExpand } from "./helper";
import {
  configureStore,
  createAction as createActionCreator,
  createReducer,
  createAsyncThunk,
} from "@reduxjs/toolkit";

// action
export const setEnvReady = createAsyncThunk("SET_ENVREADY", async () => {
  console.log(898989);
  
  const checkPromise = envList.map((item) =>
    electronAPI.nodeExec(item.checkScript)
  );
  const res = await Promise.all(checkPromise);
  console.log(9999,res);
  for (let index = 0; index < envList.length; index++) {
    envList[index].status = res[index].type === "stdout";
  }
  return envList;
});
export const setDevice = createAsyncThunk("SET_DEVICE", async (deviceId) => {
  if (!deviceId) {
    return null;
  }
  let devicesInfo = await electronAPI.getDeviceProp(deviceId);
  for (const key in devicesInfo) {
    const expand = deviceInfoExpand[key];
    if (expand) {
      devicesInfo[key] = {
        ...expand,
        value: devicesInfo[key], // 这个值是为了渲染的
      };
    }
  }
  const memAndDisk = await electronAPI.getMemAndDisk(deviceId);
  devicesInfo = {
    ...devicesInfo,
    mem: {
      label: "运存",
      value: memAndDisk.memory + " G",
    },
    disk: {
      label: "硬盘",
      value: memAndDisk.disk.size + " G",
    },
  };
  const screen = await electronAPI.screen(deviceId);
  devicesInfo["screen"] = screen + "?time=" + new Date().getTime();
  return devicesInfo;
});
export const setScreen = createAsyncThunk("SET_SCREEN", async (deviceId) => {
  if (!deviceId) {
    return null;
  }
  const screen = await electronAPI.screen(deviceId);
  return screen + "?time=" + new Date().getTime();
});

// state
const initialState = {
  device: null,
  envReady: null,
};

// reducer
const reducer = createReducer(initialState, (builder) => {
  builder
    // .addCase(setDevice, (state, action) => {
    //     state.device = action.payload;
    // })
    .addCase(setDevice.fulfilled, (state, action) => {
      // 异步方法的成功的状态
      state.device = action.payload;
    })
    .addCase(setEnvReady.fulfilled, (state, action) => {
      // 异步方法的成功的状态
      state.envReady = action.payload;
    })
    .addCase(setScreen.fulfilled, (state, action) => {
      // 异步方法的成功的状态
      state.device.screen = action.payload;
      console.log(state.device.screen);
    });
});

// store
export default configureStore({ reducer });
